// use rocket::{catch, catcher, delete, get, put, post, routes, catchers, build};
use serde_json::{json, Value};
use std::fs;
use sqlx;
use std::env;
use std::fs::File;
use std::io::Read;
use serde::Deserialize;
use sqlx::postgres::PgRow;
use sqlx::{postgres::PgPoolOptions, Executor, postgres::PgPool, Row};
use sqlx::FromRow;
use chrono::Local;
//日志
#[macro_use]
extern crate log;
extern crate env_logger;
// use include_dir::{include_dir, Dir};
// use log::{debug, error, info, trace, warn};
use std::io::Write;
use std::net::Ipv4Addr;
use rocket::Config;


#[macro_use] extern crate rocket;



//引入FileServer结构体
// use rocket::fs::FileServer;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}
//
// #[launch]
// fn rocket() -> _ {
//     rocket::build().mount("/", routes![index])
// }
//


// #[get("/")]
// fn index() -> &'static str {
//     "首页"
// }
//
// #[get("/b")]
// async fn get_res_users() -> Value {
//     json!("list!")
// }
//
// #[get("/a")]
// async fn put_res_users() -> Value {
//     json!("list!")
// }
//
#[catch(404)]
async fn not_found() -> Value {
    json!("Not found!")
}


#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
    //日志初始化
    init_logger();
    info!("starting up");
    // log4rs::init_file("log4rs.yaml", Default::default()).unwrap();

    //系统配置信息
    let _name = env!("CARGO_PKG_NAME");
    let _version = env!("CARGO_PKG_VERSION");
    let _author = env!("CARGO_PKG_AUTHORS");
    // println!("{} {} {}", &name, &version, &author);

    // let static_files: Dir = include_dir!("public");


    //登陆返回
    // let s = addons::users::res_users::login("admin".to_string(), "1".to_string()).await;


    // let mut  config = Config::default();
    // config.address = Ipv4Addr::new(106, 14, 155, 204).into();
    // config.port = 8000;


    // let connection_str = env::var("DATABASE_URL")
    //     .expect("数据库连接字符串获取失败，请检查env文件是否已配置数据库连接字符串");
    // println!("数据库连接字符串是：{}", connection_str);
    // let pool = PgPoolOptions::new()
    //     .max_connections(5)
    //     .connect(&connection_str)
    //     .await?;
    //





    //
    let _rocket = rocket::build()
    // let _rocket = rocket::custom(config)
        .mount("/", routes![index])
        // .mount("/public", FileServer::from("public/"))
        .mount("/user", routes![addons::users::res_users::browse,addons::users::res_users::page,addons::users::res_users::create])
        // .mount("/res_users", routes![get_res_users,put_res_users])
        .register("/", catchers![not_found])
        .launch().await?;
    Ok(())
}

fn init_logger() {
    use env_logger::fmt::Color;
    use env_logger::Env;
    use log::LevelFilter;

    let env = Env::default().filter_or("MY_LOG_LEVEL", "debug");
    // 设置日志打印格式
    env_logger::Builder::from_env(env)
        .format(|buf, record| {
            let level_color = match record.level() {
                log::Level::Error => Color::Red,
                log::Level::Warn => Color::Yellow,
                log::Level::Info => Color::Green,
                log::Level::Debug | log::Level::Trace => Color::Cyan,
            };

            let mut level_style = buf.style();
            level_style.set_color(level_color).set_bold(true);

            let mut style = buf.style();
            style.set_color(Color::White).set_dimmed(true);

            writeln!(
                buf,
                "{} {} [ {} ] {}",
                Local::now().format("%Y-%m-%d %H:%M:%S"),
                level_style.value(record.level()),
                style.value(record.module_path().unwrap_or("<unnamed>")),
                record.args()
            )
        })
        .filter(None, LevelFilter::Debug)
        .init();
    info!("env_logger initialized.");
}
